﻿using HuaweiCloud.Dotnet.Samples.Common.Cache.Extension;
using HuaweiCloud.Dotnet.Samples.ESports.Common.Messages;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Entities;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Manager;
using MassTransit;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;

namespace HuaweiCloud.Dotnet.Samples.ESports.Main.Consumers
{

    public class RankInfoConsumer : IConsumer<UpdateStepInfo>
    {
        private readonly IDistributedCache _cache;
        private readonly IDeviceManager _manager;
        private string _key = RedisConst.Rank;
        public RankInfoConsumer(IDistributedCache cache, IDeviceManager manager)
        {
            _cache = cache;
            _manager = manager;
        }
        public async Task Consume(ConsumeContext<UpdateStepInfo> context)
        {
            var msg = context.Message;
            if (msg == null || msg.DeviceId == null) 
                return;
            // 通过设备Id来获取对应的用户Id
            var userId = await _manager.GetUserIdByDeviceIdAsync(Guid.Parse(msg.DeviceId));
            if (userId == null)
                return;
            // 获取消息产生的时间
            var ds = msg.Date.Split("-").Select(x => Convert.ToInt32(x)).ToArray();
            var expired = new DateTime(ds[0], ds[1], ds[2]);
            // 排行榜过期时间为次日凌晨0点
            expired = expired.AddDays(1);
            if (expired < DateTime.Now)
                return;
            var option = new DistributedCacheEntryOptions()
            {
               AbsoluteExpiration = new DateTimeOffset(expired)
            };
            // 生成缓存的Key
            var key = $"{_key}-{msg.Date}";
            // 从缓存获取排行榜
            var temp = await _cache.GetAsync<Rank>(key);
            temp ??= new Rank();
            var data = temp.Data;
            // 更新排行榜中用户的步数
            if (data.ContainsKey(userId.Value))
            {
                if(msg.Count > data[userId.Value])
                    data[userId.Value] = msg.Count;
            }
            else
                data.Add(userId.Value, msg.Count);
            // 把结果写回缓存
            await _cache.SetAsync(key, temp, option);
        }
    }
}
